﻿var async = require( 'async' );
var sql = require( 'node-sqlserver' );
var path = require('path');
var dbContext = require( "../DataAccess/dbContext" );
var commonImpl = require( path.join( __dirname ,"CommonImpl") );
var util = require( '../Utils/utility' );
var workflow = require( '../Workflow/Vacation/VacationFlow' );

/*
 * 获取我申请的休假列表
 */
exports.GetMyVacationList = function ( EmployeeNo, successCall ) {

    dbContext.openHRConn( function ( conn ) {

        conn.query( "select a.*,b.LeaveType,c.status as AppStatus from vacationbasicinfo a left join aLeaveType b on a.LeaveTypeId = b.id left join application c on c.Id = a.applicationid where a.empNo =  ?",
            [EmployeeNo],
            function ( err, rows ) {
                if ( err ) {
                    console.log( "Select in DB Error: " + err );
                }

                if ( typeof successCall == "function" ) {
                    successCall( rows );
                }
            });
    });

};


/*
 * 获取我的待办
 */
exports.GetMyWorkList = function ( EmpID, successCall ) {

    dbContext.openHRConn( function( conn ){
        
        conn.query( 
            "select a.*,d.LeaveType,b.status as AppStatus,c.Node as Node from vacationbasicinfo a left join application b on a.applicationid = b.id left join task c on b.id = c.applicationid left join aLeaveType d on a.Leavetypeid = d.id where b.status = 1 and c.operatorid = 0 and c.approcedEmpid = ?",
            [EmpID],
            function( err, rows){
                if ( err ) {
                    err = "GetMyWorkList:" + err;
                    console.log( "Select in DB Error: " + err );
                }

                if ( typeof successCall == "function" ) {
                    successCall( rows );
                }
            });
            
    });

};


exports.GetVacationById = function( vacationID, successCall){
    
    dbContext.openHRConn( function ( conn ) {
        
        conn.query( 
            "select * from vacationbasicinfo where id = ?",
            [vacationID],
            function( err, rows ){

                 if ( err ) {
                    err = "GetVacationById:" + err;
                    console.log( "Select in DB Error: " + err );
                }
    
                var result = null;

                if( rows!= null && rows.length > 0) result = rows[0];

                if ( typeof successCall == "function" ) successCall( result );

            });
            
    });
        
};

/*
 * 发起休假流程
 */
exports.Submit = function ( VacationModel, successCall ) {

    var application = {
        ApplicationEmpID: VacationModel.ProposerId || '',
        CreateTime: new Date(),
        CreateEmpId: VacationModel.ProposerId || '',
        Status: util.AppStatus.Pending,
        BusinessType: util.BusinessType.Vacation
    };

    dbContext.openHRConn( function ( conn ) {

        var applicationID = 0,
            key = new Date().getTime().toString();

        async.series(
            {
                insertApplication: function ( callback ) {

                    conn.query(
                        "insert into Application(ApplicationEmpID,GuidKey,CreateTime,CreateEmpId,Status,BusinessType) values(?,?,?,?,?,?);",
                        [
                            application.ApplicationEmpID,
                            key,
                            application.CreateTime,
                            application.CreateEmpId,
                            application.Status,
                            application.BusinessType
                        ],
                        function ( err, rows ) {

                            if ( err ) {
                                err = "insertApplication:" + err;
                                console.log( "Select in DB Error: " + err );
                            }

                            callback( err, rows );
                        });

                },

                getApplicationID: function ( callback ) {

                    conn.query(
                        "select Id from application where GuidKey = ?",
                        [key],
                        function ( err, rows ) {

                            if ( err ) {
                                err = "getApplicationID:" + err;
                                console.log( "Select in DB Error: " + err );
                            }

                            if ( rows && rows.length > 0 ) {
                                applicationID = rows[0]["Id"];
                            }

                            callback( err, rows );
                        });

                },

                insertVacationBasicInfo: function ( callback ) {

                    conn.query(
                        "insert into VacationBasicInfo(ProposerId,empName,empNo,LeaveTypeId,LeaveBeginTime,LeaveBeginLength,LeaveEndTime,LeaveEndLength,TotalTimeSpan,SettlementLength,ReasonForLeave,UploadFilePath,ApplicationId) values(?,?,?,?,?,?,?,?,?,?,?,?,?)",
                        [
                            VacationModel.ProposerId || '',
                            VacationModel.empName || '',
                            VacationModel.empNo || '',
                            VacationModel.LeaveTypeId || 0,
                            new Date( VacationModel.LeaveBeginTime ),
                            VacationModel.LeaveBeginLength || 0,
                            new Date( VacationModel.LeaveEndTime ),
                            VacationModel.LeaveEndLength || 0,
                            VacationModel.TotalTimeSpan || 0,
                            VacationModel.SettlementLength || 0,
                            VacationModel.ReasonForLeave || '',
                            VacationModel.UploadFilePath || '',
                            applicationID
                        ],
                        function ( err, rows ) {
                            if ( err ) {
                                err = "insertVacationBasicInfo:" + err;
                                console.log( "Select in DB Error: " + err );
                            }
                            callback( err, rows );
                        });

                },

                startWorkflow: function ( callback ) {
                    workflow.Start( { ApplicationID: applicationID, CreatorID: VacationModel.ProposerId }, function ( err, result ) {
                        callback( err, result );
                    });
                },

                insertApplicatioAction: function ( callback ) {

                    commonImpl.insertApplicationAction(
                    {
                          ApplicationID:  applicationID,
                          Node : util.VacationNode.Start,
                          Action: util.Action.Submit,
                          ActionUserID: VacationModel.ProposerId,
                          ActionUserName : VacationModel.empName,
                          Comment: ""
                    },
                    function( err, rows ){

                        callback( err, rows );

                    });

                }
            },

            function ( err, result ) {
                //return bool of operate
                if ( successCall && typeof successCall == "function" ) successCall( err, err != "" || err != null );
            });

    });


};

/*
 * 审批同意
 */
exports.Approve = function( parameters, successCall ){
    dbContext.openHRConn( function ( conn ) {
        
        async.series(
        {
            approveWorkflow: function( callback ){
                    
                workflow.Approve( parameters, function( err, result ){
                    
                    callback( err, result);
                        
                });
            },
            
            insertApplicationAction:function( callback ){
                
                commonImpl.insertApplicationAction(
                {
                        ApplicationID:  parameters.ApplicationID,
                        Node : parameters.Node,
                        Action: util.Action.Approve,
                        ActionUserID: parameters.OperatorID,
                        ActionUserName : parameters.ActionUserName,
                        Comment: ""
                },
                function( err, rows ){

                    callback( err, rows );

                });
            }    
        },
        function( err, results ){

            if ( successCall && typeof successCall == "function" ) successCall( err, err != "" || err != null );
        });
            
    });
};

/*
 * 审批拒绝
 */
exports.Reject = function( parameters, successCall){
    
    dbContext.openHRConn( function ( conn ) {
        
        async.series(
        {
            rejectWorkflow: function( callback ){
                    
                workflow.Reject( parameters, function( err, result ){
                    
                    callback( err, result);
                        
                });
            },
            
            insertApplicationAction:function( callback ){
                
                commonImpl.insertApplicationAction(
                {
                    ApplicationID:  parameters.ApplicationID,
                    Node : parameters.Node,
                    Action: util.Action.Reject,
                    ActionUserID: parameters.OperatorID,
                    ActionUserName : parameters.ActionUserName,
                    Comment: ""
                },
                function( err, rows ){

                    callback( err, rows );

                });
            }    
        },
        function( err, results ){

            if ( successCall && typeof successCall == "function" ) successCall( err, err != "" || err != null );
        });
            
    });
        
};